package daos.db;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;

public class Conexion {

    /*
	 * The database is located in the same directory where this program is being
	 * run. Alternately one can specify the absolute path of the database location
	 */
	private static String DBNAME="testSpringDB";

	/**
	 * Derby network server port ; default is 1527
	 */
	private static int NETWORKSERVER_PORT=1527;


	/**
	 * Derby Network Client Driver class names
	 */
	public static final String DERBY_CLIENT_DRIVER = "org.apache.derby.jdbc.ClientDriver";
	private static final String DERBY_CLIENT_DS = "org.apache.derby.jdbc.ClientDataSource";

    // URL for the Derby client JDBC driver.
    private static final String DERBY_CLIENT_URL= "jdbc:derby://localhost:"+ NETWORKSERVER_PORT+"/"+DBNAME+";create=true";

    // Default to using the Derby Client JDBC Driver for database connections
    String url = DERBY_CLIENT_URL;
    String jdbcDriver = DERBY_CLIENT_DRIVER;
    String jdbcDataSource = DERBY_CLIENT_DS;
    
    Connection conn = null;

	public Connection getConnected() throws SQLException{
		try {
			this.loadDriver();
			conn = getClientDriverManagerConnection();
			return conn;
		} catch (Exception sqle) {
			System.out.println("Failure making connection: " + sqle);
			sqle.printStackTrace();
		}
		return null;
	}

	/**
	 * Load the appropriate JDBC driver
	 */
	private void loadDriver()
		throws Exception
	{
		// Load the Driver
		Class.forName(jdbcDriver).newInstance();
	}

	/**
	 * Get a client connection using the DriverManager
	 * @pre The JDBC driver must have been loaded before calling this method
	 * @return Connection	client database connection
	 */
	private Connection getClientDriverManagerConnection() throws Exception
	{
		// See Derby documentation for description of properties that may be set
		//  in the context of the network server.
		Properties properties = new java.util.Properties();

		// The user and password properties are a must, required by JCC
		properties.setProperty("user","test");
		properties.setProperty("password","test");

		// Get database connection  via DriverManager api
		Connection conn = DriverManager.getConnection(url,properties); 

		return conn;
	}
}